import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Canvas, Button } from '@tarojs/components'
import WeCropper from 'we-cropper'
import './index.less'

export default class CropperPage extends Component {
  cropper: any = null
  state: any = { src: '', canvasW: 0, canvasH: 0 }

  componentDidMount() {
    // 从路由参数读取图片
    const params = Taro.getCurrentInstance()?.router?.params || {}
    const src = decodeURIComponent(params.src || '')
    const sys = Taro.getSystemInfoSync()
    const canvasW = sys.windowWidth
    const canvasH = Math.round(sys.windowHeight * 0.7)
    this.setState({ src, canvasW, canvasH }, () => {
      this.initCropper()
    })
  }

  initCropper() {
    const { src } = this.state as any
    const deviceWidth = this.state.canvasW || Taro.getSystemInfoSync().windowWidth
    const deviceHeight = this.state.canvasH || Math.round(deviceWidth * 1.2)
    const cropperOptions = {
      id: 'cropper',
      width: deviceWidth,
      height: deviceHeight,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: 0,
        y: 0,
        width: deviceWidth,
        height: Math.round(deviceHeight * 0.8),
      }
    }

    // @ts-ignore
    this.cropper = new WeCropper(cropperOptions)
      .on('ready', () => {
        if (src) {
          this.cropper.pushOrign(src)
        }
      })
  }

  handleConfirm = () => {
    if (!this.cropper) return
    this.cropper.getCropperImage((tempFilePath: string) => {
      if (!tempFilePath) {
        Taro.showToast({ title: '裁剪失败', icon: 'none' })
        return
      }
      // 获取裁剪后的图片信息
      Taro.getImageInfo({ src: tempFilePath }).then((info: any) => {
        const eventChannel = (Taro.getCurrentInstance() as any).eventChannel
        // 返回给调用页面
        const payload = { tempFilePath, width: info.width, height: info.height }
        if (eventChannel && typeof eventChannel.emit === 'function') {
          eventChannel.emit('cropDone', payload)
        }
        Taro.navigateBack()
      }).catch(() => {
        Taro.showToast({ title: '获取裁剪图失败', icon: 'none' })
      })
    })
  }

  handleCancel = () => {
    Taro.navigateBack()
  }

  render() {
    const { canvasW, canvasH } = this.state as any
    return (
      <View className='cropper-page' style={{ height: '100vh' }}>
        <Canvas canvasId='cropper' style={{ width: `${canvasW}px`, height: `${canvasH}px` }} />
        <View className='cropper-actions'>
          <Button onClick={this.handleCancel}>取消</Button>
          <Button onClick={this.handleConfirm}>确认</Button>
        </View>
      </View>
    )
  }
}


